<template>
  <div id="Device">
    <div class="search">
      <div class="searchForm">
        <el-form :inline="true" :model="iptForm" class="demo-form-inline">
          <el-form-item>
            <el-input
              style="width: 1.1rem"
              class="input"
              clearable
              v-model="iptForm.keyWord"
              placeholder="设备ID/设备名称"
              :suffix-icon="Search"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-select style="width: 0.7rem" clearable v-model="iptForm.status" filterable placeholder="设备状态">
              <el-option v-for="item in statusOpt" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select style="width: 0.7rem" clearable v-model="iptForm.type" filterable placeholder="气体类型">
              <el-option v-for="item in typeList" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select style="width: 0.7rem" clearable v-model="iptForm.projectId" filterable placeholder="企业">
              <el-option v-for="item in ProjectList" :key="item.id" :label="item.name" :value="item.id"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-cascader
              filterable
              clearable
              v-model="address"
              placeholder="选择地址"
              :options="areaList"
              :props="{
                label: 'name',
                value: 'name',
                children: 'districts',
              }"
              @change="areaChg"
            />
          </el-form-item>
          <el-form-item>
            <el-date-picker
              style="width: 1.5rem"
              v-model="value1"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :disabledDate="disabledDate"
              @change="pickerChe"
            />
          </el-form-item>
        </el-form>
      </div>
      <div class="total">
        <el-button style="color: #94ceff; padding: 12px 20px; height: 42px" @click="resetForm">重置</el-button>
        <el-button class="searchBtn" style="color: #94ceff; padding: 12px 20px; height: 42px" @click="search"
          >搜索</el-button
        >
      </div>
    </div>

    <div class="table">
      <el-table
        v-loading="loading"
        ref="tableRef"
        element-loading-background="rgba(0, 0, 0, 0.3)"
        :data="tableData"
        :max-height="tableHeight"
        :header-cell-style="{
          background: '#082c57',
          textAlign: 'center',
          borderColor: 'transparent',
        }"
        :cell-style="{
          borderColor: 'transparent',
        }"
        style="width: 100%"
      >
        <el-table-column label="设备ID/设备名称" width="220">
          <template #default="scope">
            <span
              @click="deviceInfo(scope.row.deviceId)"
              style="color: #94ceff; text-decoration: underline; cursor: pointer"
            >
              {{ scope.row.deviceId }}
            </span>
            <div>{{ scope.row.name }}</div>
          </template>
        </el-table-column>
        <el-table-column label="设备状态" show-overflow-tooltip>
          <template #default="scope">
            <el-tag
              v-if="scope.row.warnSatus == 1"
              effect="dark"
              :color="
                scope.row.warnLevel == 10
                  ? 'rgba(245, 108, 108,0.3)'
                  : scope.row.warnLevel == 11
                  ? 'rgba(245, 108, 108,0.3)'
                  : scope.row.warnLevel == 6
                  ? 'rgba(254, 211, 106, 0.26)'
                  : scope.row.warnLevel == 9 || scope.row.status == 0
                  ? 'rgba(255, 255, 255, 0.26)'
                  : 'rgba(111, 227, 186, 0.26)'
              "
              :style="{
                color:
                  scope.row.warnLevel == 10 || scope.row.warnLevel == 11
                    ? '#e05861'
                    : scope.row.warnLevel == 6
                    ? '#fed36a'
                    : scope.row.warnLevel == 9 || scope.row.status == 0
                    ? '#d1eaff'
                    : '#6fe3ba',
                borderColor: 'transparent',
              }"
            >
              {{
                scope.row.warnLevel == 10 || scope.row.warnLevel == 11
                  ? '报警'
                  : scope.row.warnLevel == 6
                  ? '故障'
                  : scope.row.warnLevel == 9 || scope.row.status == 0
                  ? '离线'
                  : ''
              }}
            </el-tag>
            <el-tag
              v-else
              :color="scope.row.status == 1 ? 'rgba(111, 227, 186, 0.26)' : 'rgba(255, 255, 255, 0.26)'"
              :style="{
                color: scope.row.status == 1 ? '#6fe3ba' : '#d1eaff',
                borderColor: 'transparent',
              }"
              >{{ scope.row.status == 1 ? '正常' : '离线' }}</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column label="气体类型" width="120" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ scope.row.type == 'oxygen' ? '氧气' : '可燃气' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="所属企业" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ scope.row.project_name || '- -' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="地址" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ scope.row.location || '- -' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="最近连接时间" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ scope.row.latestDate || '- -' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ scope.row.createdDate || '- -' }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button
              style="color: #0cbcff; padding: 0; border: none"
              size="small"
              @click="deviceInfo(scope.row.deviceId)"
            >
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <div class="total">
          <div class="ok" style="color: #94ceff">
            总数
            <span>{{ deviceStatus?.total || 0 }}</span>
          </div>
          <div class="ok" style="color: #6fe3ba">
            ● 正常
            <span>{{ deviceStatus?.normalCount || 0 }}</span>
          </div>
          <div class="ok" style="color: #e05861">
            ● 报警
            <span>{{ deviceStatus?.lowCount + deviceStatus?.highCount || 0 }}</span>
          </div>
          <div class="ok" style="color: #fed36a">
            ● 故障 <span>{{ deviceStatus?.errorCount || 0 }}</span>
          </div>
          <div class="ok" style="color: #cfcfcf">
            ● 离线 <span>{{ deviceStatus?.offlineCount || 0 }}</span>
          </div>
        </div>
        <el-pagination
          background
          v-model:current-page="currentPage"
          v-model:page-size="iptForm.size"
          layout="total,->, prev, pager, next, sizes, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        >
        </el-pagination>
      </div>
    </div>
  </div>
</template>
<script setup>
import Warn from '@/utils/warn'
import Device from '@/utils/device'
import area from '../assets/areaList.json' //
import { reactive, ref, onMounted, onBeforeUnmount, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { Search } from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import { ElMessage } from 'element-plus'

const router = useRouter()
const typeList = [
  {
    value: 'oxygen',
    label: '氧气',
  },
  {
    value: 'methane',
    label: '可燃气',
  },
]

const statusOpt = [
  {
    value: 1,
    label: '正常',
  },
  {
    value: 6,
    label: '报警',
  },
  {
    value: 3,
    label: '故障',
  },
  {
    value: 2,
    label: '离线',
  },
]
const defaultTimes = ref(['00:00:00', '23:59:59'])
function disabledDate(time) {
  let current_time = dayjs(new Date()).format('YYYY-MM-DD') + ' 23:59:59'
  let t = new Date(current_time.replace(/-/g, '/')).getTime() //此处转换-为/是为了兼容ie,ie在转换时间戳时不支持2022-01-07格式
  return time.getTime() > t
  // return time.getTime() > new Date().getTime() //禁止选择今天以后的时间
}

const total = ref(1)
const currentPage = ref(1)

let iptForm = reactive({
  page: 0,
  size: 10,
  keyWord: '',
  projectId: '',
  type: '',
  status: '',
  province: '',
  city: '',
  area: '',
  street: '',
  start: '',
  end: '',
})
let iptFormObj = reactive({
  page: 0,
  size: 10,
  keyWord: '',
  projectId: '',
  type: '',
  status: '',
  province: '',
  city: '',
  area: '',
  street: '',
  start: '',
  end: '',
})
const tableData = ref([])
const warnRestore = ref({})
const warnResponse = ref({})
const warntotal = ref(0)
const ProjectList = ref([])
const areaList = ref([])
const deviceStatus = ref({})
const loading = ref(false)

// 列表
async function DeviceList(e) {
  try {
    clearInterval(timer)
    timer = null
    if (e) {
      loading.value = true
    }
    let res = await Device.postDevice(iptFormObj)
    loading.value = false

    total.value = res.data.total
    tableData.value = res.data.items
    if (tableData.value.length) {
      // data排序
      tableData.value = tableData.value.sort((a, b) => {
        return b.id - a.id
      })
    }
    refresh()
  } catch (error) {}
}
function areaChg(e) {
  ;[iptForm.province, iptForm.city, iptForm.area, iptForm.street] = e
  console.log(iptForm)
}
// 恢复和未恢复数量
async function getInformation() {
  try {
    // let data = {
    //   projectId: iptForm.projectId,
    //   province: iptForm.province,
    //   city: iptForm.city,
    //   area: iptForm.area,
    // }
    let data = {
      projectId: '',
      province: '',
      city: '',
      area: '',
    }
    let res = await Device.postDeviceStatus(data)
    deviceStatus.value = res.data
  } catch (error) {}
}

//切换页码
function handleCurrentChange(val) {
  // console.log("第几页", val);
  iptForm.page = val - 1
  iptFormObj = JSON.parse(JSON.stringify(iptForm))

  DeviceList(true)
}
//切换条数
function handleSizeChange(val) {
  // console.log(val, "条");
  iptForm.size = val
  iptFormObj = JSON.parse(JSON.stringify(iptForm))

  DeviceList(true)
}
async function getProjectList() {
  try {
    let res = await Warn.getProject()
    ProjectList.value = res.data
    areaList.value = filterEmptyChildren(area)
  } catch (error) {}
}
function filterEmptyChildren(arr) {
  let newArr = arr
  newArr.map(e => {
    if (e.districts?.length) {
      filterEmptyChildren(e.districts)
    } else {
      delete e.districts
    }
    return e
  })
  return newArr
}
function search() {
  currentPage.value = 1
  iptForm.page = 0
  iptFormObj = JSON.parse(JSON.stringify(iptForm))
  DeviceList(true)
}
const address = ref()
function resetForm() {
  iptForm.keyWord = ''
  iptForm.projectId = ''
  iptForm.type = ''
  iptForm.status = ''
  iptForm.province = ''
  iptForm.city = ''
  iptForm.area = ''
  iptForm.street = ''
  iptForm.start = ''
  iptForm.end = ''
  iptForm.page = 0
  iptForm.size = 10
  value1.value = ''
  address.value = ''
  currentPage.value = 1
  iptFormObj = JSON.parse(JSON.stringify(iptForm))

  DeviceList(true)
}
const value1 = ref('')

// 选择时间
function pickerChe(e) {
  if (e) {
    let start = dayjs(e[0]).valueOf()
    let end = dayjs(e[1]).valueOf()
    end = new Date(dayjs(end).format('YYYY-MM-DD 23:59:59')).getTime()
    iptForm.start = start
    iptForm.end = end
  } else {
    iptForm.start = ''
    iptForm.end = ''
  }
}

function deviceInfo(id) {
  router.push({
    path: '/device/deviceInfo',
    query: { id },
  })
}
let timer = null
function refresh() {
  timer = setInterval(() => {
    DeviceList()
  }, 3000)
}
const tableHeight = ref(500)
const tableRef = ref()
onMounted(() => {
  nextTick(() => {
    tableHeight.value = window.innerHeight - tableRef.value.$el.offsetTop - 90 //窗口高度 - 表格距离顶部距离 - 需求高度
    tableRef.value.doLayout() //更新表格 防止表格内容变化表格异常情况
    // 监听窗口大小变化
    window.onresize = function () {
      if (tableRef.value !== null) {
        console.log(tableRef.value, 'tableRef.value')
        tableHeight.value = window.innerHeight - tableRef.value.$el.offsetTop - 90
        tableRef.value.doLayout()
      }
    }
  })
  getInformation()
  DeviceList(true)
  getProjectList()
})

onBeforeUnmount(() => {
  clearInterval(timer)
  timer = null
})
</script>
<style lang="scss" scoped>
#Device {
  width: 100%;
  padding: 15px 20px 20px;
  // text-align: left;
  box-sizing: border-box;
  // background: #f2f2f2;
  // padding-top:100px ;
  :deep(.el-loading-spinner) {
    margin-top: 0;
  }

  :deep(.search) {
    display: flex;
    justify-content: space-between;
    // align-items: center;
    align-items: flex-end;

    .searchForm {
      width: 80%;
      // .iptkeyWord {
      //   .el-icon-search {
      //     display: none;
      //   }
      // }
    }
    .total {
      width: 10%;
      display: flex;
      justify-content: space-between;
      margin-bottom: 20px;
      font-size: 18px;
      .el-button {
        border: none;
        border-radius: 12px;
        background: rgba(4, 26, 59, 1);
      }
    }
    .el-form {
      display: flex;
      justify-content: space-between;
      align-items: center;
      flex-wrap: nowrap;
      .el-form-item {
        // width: 32%;
        // margin-right: 0;
        .el-form-item__content {
          height: 40px;
        }
      }

      // .el-range-editor.el-input__inner {
      //   width: 100%;
      // }
      // .el-form-item__content {
      //   display: flex;
      // }
      // .searchName-select {
      //   .el-input__inner {
      //     border-radius: 4px 0px 0px 4px;
      //   }
      // }
      // .select-wrap {
      //   flex: 1;
      //   .el-input__inner {
      //     border-radius: 0px 4px 4px 0px;
      //   }
      // }
    }
  }

  :deep(.table) {
    .el-table {
      margin-bottom: 20px;
      background: transparent;

      .el-table__header-wrapper {
        thead {
          th {
            div {
              background: linear-gradient(180deg, rgba(5, 156, 255, 1) 37%, rgba(51, 248, 242, 1) 100%);
              -webkit-background-clip: text;
              color: transparent;
            }
          }
        }
      }
      .el-table__cell {
        padding: 0;
        height: 60px;
        background: transparent;
      }

      td.el-table__cell div {
        text-align: center;
        color: #94ceff;
        font-size: 16px;
        font-weight: 400;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
    .el-button {
      &:hover {
        border: none;
      }
    }
    .el-table__row {
      background: transparent;
    }
  }
  .pagination {
    display: flex;
    align-items: center;
    justify-content: space-between;
    .total {
      display: flex;
      font-size: 16px;
      font-weight: 400;
      letter-spacing: 0px;
      div {
        &:nth-child(1) {
          margin-left: 30px;
        }
      }
      span {
        margin: 0 12px;
        &:nth-child(1) {
          margin-right: 30px;
        }
      }
    }
  }
  :deep(.dialog) {
    .el-dialog__body {
      padding-left: 0;
      padding-bottom: 0;
    }
  }
  // .input {
  //   :deep(.el-input__inner) {
  //     padding-right: 50px;
  //   }
  // }
}
</style>

